package com.heima.itcast;

import org.apache.kafka.clients.producer.*;
import org.junit.Test;

import java.util.Properties;
import java.util.concurrent.ExecutionException;

public class ProducerQuickStart {

    @Test
    public void sendMsg() throws ExecutionException, InterruptedException {

        //2. 编写配置
        Properties properties = new Properties();
        properties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "192.168.200.130:9092");
        properties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer");
        properties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer");

        //1. 核心对象的创建
        KafkaProducer<String, String> producer = new KafkaProducer<String, String>(properties);

        //3. 发送消息
        /*for (int i =0; i<100; i++){
            ProducerRecord<String, String> record = new ProducerRecord<>("topic", "hello", "kafka" + i);
            producer.send(record);
        }*/
        ProducerRecord<String, String> record = new ProducerRecord<>("itcast-topic-input", "hello world ,hello itcast");
        RecordMetadata recordMetadata = producer.send(record).get();
        System.out.println(recordMetadata.offset());

        //4. 关闭链接
        producer.close();
    }


    @Test
    public void sendASyncMsg() throws ExecutionException, InterruptedException {

        //2. 编写配置
        Properties properties = new Properties();
        properties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "192.168.200.130:9092");
        properties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer");
        properties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer");
        properties.put(ProducerConfig.ACKS_CONFIG, "all");
        properties.put(ProducerConfig.RETRIES_CONFIG, 10);
        properties.put(ProducerConfig.COMPRESSION_TYPE_CONFIG, "lz4");

        //1. 核心对象的创建
        KafkaProducer<String, String> producer = new KafkaProducer<String, String>(properties);

        //3. 发送消息
        ProducerRecord<String, String> record = new ProducerRecord<>("topic", "hello", "kafka");
        producer.send(record, new Callback() {
            @Override
            public void onCompletion(RecordMetadata metadata, Exception e) {
                if(null != e){
                    e.printStackTrace();
                }

                System.out.println(metadata.offset());
            }
        });

        //4. 关闭链接
        producer.close();
    }


}
